const qs = require('qs')
const { createHash } = require('crypto')
const request = require('../utils/request')
const wechatConfig = require('../config/wechat')
const Cache = require('../utils/cache')

async function getWechatAccessToken(ctx) {
  const cache = Cache.getInstance()
  const { appId, appsecret, expiresIn, noncestr } = wechatConfig

  let accessToken = jsapiTicket = null;

  if (!cache.get('accessToken')) {

    const { access_token } = await request.get(
      `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appsecret}`
    )
    const { ticket } = await request.get(
      `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`
    )
    
    cache.set('accessToken', access_token, expiresIn)
    cache.set('jsapiTicket', ticket, expiresIn)
  }

  accessToken = cache.get('accessToken')
  jsapiTicket = cache.get('jsapiTicket')


  const timestamp = new Date().getTime()
  const objs = {
    noncestr,
    timestamp,
    jsapi_ticket: jsapiTicket,
    url: ctx.request.href,
  }
  const arry = Object.keys(objs).map((key) => (`${key}=${objs[key]}`))
  const content = arry.sort().join('&')
  const signature = createHash('sha1').update(content).digest('hex')

  ctx.body = {
    appId,
    noncestr,
    timestamp,
    signature,
    expiresIn,
  }
}

module.exports = {
  getWechatAccessToken
}